import 'dotenv/config';           //这是包的作用是读取.env文件然后写入process.env.JWT_SECRET_KEY
import path from 'path';
import express, { Express, Request, Response, NextFunction } from 'express';    //启服务
import cors from 'cors';          //用来跨域的
import morgan from 'morgan';      //这是用来输入访问日志的
import helmet from 'helmet';      //用来进行安全过滤的
import multer from 'multer';
import * as userController from './controllers/user';
import * as orderController from './controllers/orders';

import HttpException from './exceptions/HttpException';
import errorMiddleware from './middlewares/errorMiddleware';
import loginMiddleware from './middlewares/loginMiddleware';

//指定上传文件的存储空间
const storage = multer.diskStorage({
  //指定上传的目录
  destination: path.join(__dirname, 'public', 'uploads'),
  filename(_req: Request, file: Express.Multer.File, callback) {
    // callback 第二个参数是文件名 时间戳.jpg
    callback(null, Date.now() + path.extname(file.originalname));
  }
});
// 在需要上传的地方使用这个
const upload = multer({ storage });

const app: Express = express();
// 使用中间件
app.use(cors()); // 处理跨域请求
app.use(morgan('dev')); // 开发环境打印日志
app.use(helmet());
// 处理请求
app.use(express.json());//express.json=bodyParser.json
app.use(express.urlencoded({ extended: true }));

// 配置静态文件目录,也是上传的目录
app.use(express.static(path.join(__dirname, 'public')));


// 测试接口
app.get('/', (_req, res, _next) => {
  res.json({ code: 0, message: '成功' });
});

app.post('/user/register', userController.register);
app.post('/user/login', userController.login);
app.get('/user/list', loginMiddleware, userController.userList);

// 提交订单
app.post('/order', loginMiddleware, orderController.orders)
//当服务器端接收到上传文件请求的时候，处理单文件上传。字段名avatar  request.file=Express.Multer.File
app.post('/user/uploadAvatar', upload.single('avatar'), userController.uploadAvatar);


//如果说没有匹配到任何路由，则会创建一个自定义404错误对象并传递给错误处理中间件
app.use((_req: Request, _res: Response, next: NextFunction) => {
  const error: HttpException = new HttpException(404, '尚未为此路径分配路由');
  next(error);
});
// 使用自定义中间件
app.use(errorMiddleware);


(async function () {
  const PORT = process.env.PORT || 8001;
  app.listen(PORT, () => {
    console.log(`Running on http://localhost:${PORT}`);
  })
})();
